package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("user")//别名自己取
//类名记着自己改一下
public class UserController {
    @RequestMapping("add")
    public String add(@Valid UserBean userBean, //@Volid 表示该对象的属性需要进行验证
                      BindingResult result) throws JsonProcessingException { //BindingResult用于判断验证是否通过，已绑定出错信息
        if (result.hasErrors()){//判断是否有错误消息
            //得到错误集合
            List<FieldError> list= result.getFieldErrors();
            ObjectMapper om=new ObjectMapper();
            //将错误信息转化为json字符串，发送给客户端
            String errorStr=om.writeValueAsString(list);
            return errorStr;
        }
        return "ok";
    }
}